import { createRouter, createWebHistory } from 'vue-router'
import { useUserIdStore } from '@/stores/UserId'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path:'/',
      redirect: '/square'
    },
    {
    path: '/show',
    name: 'Show',
    component: () => import('@/views/ShowView.vue'),
    meta: { requiresAuth: true }
    },
    {
    path: '/manager',
    name: 'Manager',
    component: () => import('@/views/ManagerView.vue'),
    meta: { requiresAuth: true }
    },
    {
    path: '/order',
    name: 'Order',
    component: () => import('@/views/OrderView.vue'),
    meta: { requiresAuth: true }
    },
    {
    path: '/chat',
    name: 'Chat',
    component: () => import('@/views/ChatView.vue'),
    meta: { requiresAuth: true }
    },
    {
    path: '/user',
    name: 'User',
    component: () => import('@/views/UserView.vue')
    },
    {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/user/LoginView.vue')
    },
    {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/user/RegisterView.vue')
    },
    {
    path: '/edit-profile',
    name: 'Edit',
    component: () => import('@/views/user/EditProfileView.vue'),
    meta: { requiresAuth: true }
    },
    {
    path: '/square',
    name: 'Square',
    component: () => import('@/views/SquareView.vue')
    },
    {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import('@/views/shop/ShopView.vue')
    },
    {
    path: '/checkout',
    name: 'Checkout',
    component: () => import('@/views/CheckoutView.vue'),
    meta: { requiresAuth: true }
    },
  ],
})

// 路由守卫：检查需要登录的页面
router.beforeEach((to, from, next) => {
  const userIdStore = useUserIdStore()
  
  // 如果页面需要登录验证
  if (to.meta.requiresAuth) {
    // 首先尝试从本地存储恢复状态
    if (!userIdStore.isAuthenticated) {
      console.log('🔒 页面需要登录，尝试恢复用户状态...')
      const restored = userIdStore.restoreFromStorage()
      
      if (!restored || !userIdStore.isAuthenticated) {
        console.log('❌ 用户未登录，重定向到登录页面')
        next('/login')
        return
      } else {
        console.log('✅ 用户状态已恢复，允许访问页面')
      }
    }
  }
  
  next()
})

export default router
